import { defineAsyncComponent, createVNode, render as vueRender } from 'vue';
import get from 'lodash-es/get.js';
import merge from 'lodash-es/merge.js';

export default function (content, options) {
  options = Object.assign({}, options);
  let container = document.createDocumentFragment();
  let contentInstance = null;
  let contentRef = null;

  function getGlobalAppProps(key, defaultValue) {
    return get(window.__GLOBAL_VUE_APP, key, defaultValue);
  }

  function destroy() {
    if (contentInstance) {
      vueRender(null, container);
      contentInstance.component.update();
    }
    contentInstance = null;
    contentRef = null;
    container = null;
    content = null;
    options = null;
  }

  function update(updateProps) {
    if (contentInstance) {
      if (typeof updateProps === 'function') {
        const oldProps = Object.assign({}, contentInstance.component.props);
        updateProps = updateProps(oldProps);
      }
      /* 不能让 modalInstance.component.props 失去响应式 */
      merge(contentInstance.component.props, updateProps);
      contentInstance.component.update();
    }
  }
  if (typeof content === 'function') {
    content = defineAsyncComponent(content);
  }
  const defaultProps = {
    ref: 'contentRef',
    onVnodeMounted: () => {
      contentRef = contentInstance.ctx.refs.contentRef;
    },
  };
  contentInstance = createVNode(content, Object.assign({}, defaultProps, options));
  contentInstance.appContext = getGlobalAppProps('_context') || contentInstance.appContext;
  vueRender(contentInstance, container);
  return { update, destroy };
}
